package pl.edu.pk.mech.kkbus.component;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import org.apache.commons.codec.digest.DigestUtils;

import java.util.Date;
import java.util.logging.Logger;

import pl.edu.pk.mech.kkbus.model.HistoryLog;
import pl.edu.pk.mech.kkbus.model.User;
import pl.edu.pk.mech.kkbus.service.HistoryLogService;
import pl.edu.pk.mech.kkbus.service.UserService;

@Component
public class MyAuthenticationProvider implements AuthenticationProvider {
    
    private static final Logger log = Logger.getLogger(MyAuthenticationProvider.class.getName());
    
    @Autowired
    UserService userService;
    
    @Autowired
    HistoryLogService historyLogService;

    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //Username
        Object userIdentifier = authentication.getPrincipal();        
        // Password
        Object userPassword = DigestUtils.md5Hex(String.valueOf(authentication.getCredentials()));
        
        log.info("User: " + userIdentifier);
        log.info("Password: " + userPassword);
  
        User user = userService.loadUserByEmail(userIdentifier.toString());

        if(user == null) { 
            throw new UsernameNotFoundException("User not found!");
        }
        
        if (!user.isEnabled()) {
            throw new DisabledException("Account is disabled!");
        }

        if(user.getPassword().equals(userPassword)) {
        	historyLogService.createOrUpdateHistoryLog(new HistoryLog(String.valueOf(user.getId()), new Date()));
            return new UsernamePasswordAuthenticationToken(user.getEmail(), user.getPassword(), user.getAuthorities());
        } else {
            throw new UsernameNotFoundException("Wrong password!");
        }
    }
    
    public final boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}